package org.springblade.modules.digitalization.utils;


import cn.hutool.core.io.FileUtil;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.sanselan.ImageInfo;
import org.apache.sanselan.Sanselan;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;

@Slf4j
public class ImgUtils {


	private static Pair<Integer, Integer> intGetImageDpi(File infile) {
		try {
			ImageInfo imageInfo = Sanselan.getImageInfo(infile);
			// 图像dpi获取失败则返回-1
			int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
			int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();
			return Pair.of(physicalHeightDpi, physicalHeightDpi);
		} catch (Exception e) {
			return Pair.of(-1, -1);
		}

	}

	public static void changeDpi(String filePath, int newDpi, Integer unit) {

		Pair<Integer, Integer> integerIntegerPair = intGetImageDpi(new File(filePath));
		// 相同dpi不处理
//		if (integerIntegerPair.getLeft() == newDpi && integerIntegerPair.getRight() == newDpi) {
//			log.info("{} 与目标dpi（{}）相同，不处理", filePath, newDpi);
//			return;
//		}
		File infile = null;
		try {
			infile = FileUtil.copy(filePath, filePath + "_", true);
			File outfile = new File(filePath);

			ImageReader reader = ImageIO.getImageReadersByFormatName("jpeg").next();
			FileImageInputStream fin = new FileImageInputStream(infile);
			reader.setInput(fin, true, false);

			BufferedImage image = reader.read(0);

			FileOutputStream fos = new FileOutputStream(outfile);
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(fos);
			JPEGEncodeParam jpegEncodeParam = jpegEncoder.getDefaultJPEGEncodeParam(image);
			if (unit != null) {
				jpegEncodeParam.setDensityUnit(JPEGEncodeParam.DENSITY_UNIT_DOTS_INCH);
			}
			jpegEncodeParam.setXDensity(newDpi);
			jpegEncodeParam.setYDensity(newDpi);

			jpegEncoder.setJPEGEncodeParam(jpegEncodeParam);
			jpegEncoder.encode(image, jpegEncodeParam);

			fos.close();
			fin.close();

		} catch (Exception e) {
			log.error("DPI修改出错", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (infile != null) {
					FileUtil.del(infile);
				}
			} catch (Exception e) {
				log.warn(e.getMessage(), e);
			}
		}


	}

	public static void main(String[] args) throws Exception {
		changeDpi("G:\\Users\\Administrator\\Documents\\WeChat Files\\WeChat Files\\wxid_bb9vebf4n3fn21\\FileStorage\\File\\2025-04\\111\\test.jpg", 300, null);
	    //Pair<Integer, Integer> integerIntegerPair = intGetImageDpi(new File("D:/data/img/1.jpg"));
		//System.out.println(integerIntegerPair.getLeft());
	}


}
